package com.mininglamp.mesense.utils

import java.sql.Timestamp
import java.text.{ParseException, SimpleDateFormat}
import java.util
import java.util.{Calendar, Date}
import java.util.regex.Pattern

/**
  * 日期工具类
  */
object DateUtils {
  private val EARLYDATE = "2016-01-01 00:00:00"
  // 标准日期格式
  val FMT_DATE = "yyyy-MM-dd"
  // 标准时间格式
  val FMT_TIME = "HH:mm:ss"
  // 标准日期时间格式
  val FMT_DATE_TIME = "yyyy-MM-dd HH:mm:ss"
  val FMT_DATE_TIME_3 = "yyyyMMdd HH:mm:ss"
  val FMT_DATE_TIME_2 = "yyyyMMddHHmmss"
  val FMT_DATE_TIME_4 = "yyyyMMdd"
  // 标准日期格式的格式化类
  val SDF_DATE = new SimpleDateFormat(FMT_DATE)
  // 标准时间格式的格式化类
  val SDF_TIME = new SimpleDateFormat(FMT_TIME)
  // 标准日期时间格式的格式化类
  val SDF_DATE_TIME = new SimpleDateFormat(FMT_DATE_TIME)

  /**
    * 获取间隔天数
    *
    * @param startTime
    * @param endTime
    * @return
    */
  def getIntervalDay(startTime: Date, endTime: Date): Int = {
    val cal1 = Calendar.getInstance
    cal1.setTime(startTime)
    val cal2 = Calendar.getInstance
    cal2.setTime(endTime)
    val day1 = cal1.get(Calendar.DAY_OF_YEAR)
    val day2 = cal2.get(Calendar.DAY_OF_YEAR)
    val year1 = cal1.get(Calendar.YEAR)
    val year2 = cal2.get(Calendar.YEAR)
    if (year1 != year2) { //不同年
      var timeDistance = 0
      var i = year1
      while ( {
        i < year2
      }) {
        if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) { //闰年
          timeDistance += 366
        }
        else { //不是闰年
          timeDistance += 365
        }

        {
          i += 1; i - 1
        }
      }
      timeDistance + (day2 - day1)
    }
    else { //同一年
      day2 - day1
    }
  }

  /**
    * 日期加上天数后的日期
    *
    * @param count
    * @return
    * @throws ParseException
    */
  def getEndTime(date: Date, count: Int): Date = {
    val ca = Calendar.getInstance
    ca.setTime(date)
    ca.add(Calendar.DATE, count) // count为增加的天数，可以改变的

    val currdate = ca.getTime
    currdate
  }

  /**
    * 获取当前时间的前24小时
    *
    * @param dateEnd
    * @return
    */
  def getOneDayBefore(dateEnd: Date): Date = {
    val date = Calendar.getInstance
    date.setTime(dateEnd)
    date.set(Calendar.DATE, date.get(Calendar.DATE) - 1)
    date.getTime
  }

  /**
    * 获取当前日期的前一天
    *
    * @param strDate
    * @return
    */
  def getOneDayBefore(strDate: String): String = {
    val sdf = new SimpleDateFormat("yyyy-MM-dd")
    val date = Calendar.getInstance
    try
      date.setTime(sdf.parse(strDate))
    catch {
      case e: ParseException =>
        e.printStackTrace()
    }
    date.set(Calendar.DATE, date.get(Calendar.DATE) - 1)
    sdf.format(date.getTime)
  }

  /**
    * String转timestamp
    *
    * @param time
    * @return
    */
  def formatTimestamp(time: String): Timestamp = {
    val ts = Timestamp.valueOf(time)
    ts
  }

  /**
    * long转String
    *
    * @param time
    * @return
    */
  def formatstamp(time: Long): String = {
    val ts = new Timestamp(time)
    val dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val str = dateTimeFormat.format(ts)
    str
  }

  /**
    * String转成date格式的字符串 yyyyMMddHHmm
    *
    * @param time
    * @return
    */
  def formatString(time: String): String = {
    val dateTimeFormat1 = new SimpleDateFormat("yyyyMMddHHmmss")
    val dateTimeFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    try {
      val dt = dateTimeFormat1.parse(time)
      dateTimeFormat2.format(dt)
    } catch {
      case e: ParseException =>
        e.printStackTrace()
        null
    }
  }

  def formatString2(time: String): String = {
    val dateTimeFormat1 = new SimpleDateFormat("yyyyMMddHHmmss")
    val dateTimeFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    try {
      val dt = dateTimeFormat2.parse(time)
      dateTimeFormat1.format(dt)
    } catch {
      case e: ParseException =>
        e.printStackTrace()
        null
    }
  }
  /**
    * 格式日期yyyy-MM-dd
    *
    * @return
    */
  def formatDate(date: Date): String = {
    val tempDate = Calendar.getInstance
    tempDate.setTime(date)
    val dateFormat = new SimpleDateFormat("yyyy-MM-dd")
    dateFormat.format(tempDate.getTime)
  }

  /**
    * 日期+
    *
    * @param date
    * @param days
    * @return
    */
  def addDate(date: Date, days: Int): Date = {
    val tempDate = Calendar.getInstance
    tempDate.setTime(date)
    tempDate.add(Calendar.DAY_OF_MONTH, days)
    tempDate.getTime
  }

  /**
    * 获取该日期前两个小时
    *
    * @param date
    * @param hour
    * @return
    */
  def twoHourDate(date: Date, hour: Int): Date = {
    val tempDate = Calendar.getInstance
    tempDate.setTime(date)
    tempDate.add(Calendar.HOUR_OF_DAY, hour)
    tempDate.getTime
  }
  /**
    * 获取该日期后几个小时
    *
    * @param date
    * @param hour
    * @return
    */
  def afterHourDate(date: Date, hour: Int): Date = {
    val tempDate = Calendar.getInstance
    tempDate.setTime(date)
    tempDate.add(Calendar.HOUR_OF_DAY, hour)
    tempDate.getTime
  }
  /**
    * 获取前两个小时的字符串
    *
    * @param date
    * @param hour
    * @return
    */
  def twoHourDates(date: Date, hour: Int): String = {
    val time = twoHourDate(date, hour)
    val dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val tempDate = Calendar.getInstance
    tempDate.setTime(time)
    dateTimeFormat.format(tempDate.getTime)
  }

  /**
    * 格式日期yyyyMMdd
    *
    * @return
    */
  def formatDateDefault(date: Date): String = {
    val tempDate = Calendar.getInstance
    tempDate.setTime(date)
    val dateFormat = new SimpleDateFormat("yyyyMMdd")
    dateFormat.format(tempDate.getTime)
  }

  /**
    * 日期格式yyyyMM
    *
    * @param date
    * @return
    */
  def formatDateMonth(date: Date): String = {
    val tempDate = Calendar.getInstance
    tempDate.setTime(date)
    val dateFormat = new SimpleDateFormat("yyyyMM")
    dateFormat.format(tempDate.getTime)
  }

  /**
    * 格式日期yyyy-MM-dd HH:mm:ss
    *
    * @return
    */
  def formatDateTime(date: Date): String = {
    val tempDate = Calendar.getInstance
    tempDate.setTime(date)
    val dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    dateTimeFormat.format(tempDate.getTime)
  }

  /**
    * 将date转换成制定格式的时间
    *
    * @param date
    * @param gs
    * @return
    */
  def formatDateTime(date: Date, gs: String): String = {
    val tempDate = Calendar.getInstance
    tempDate.setTime(date)
    val dateTimeFormat = new SimpleDateFormat(gs)
    dateTimeFormat.format(tempDate.getTime)
  }

  /**
    * 将String转换成制定格式的时间
    *
    * @param date
    * @param gs
    * @return
    */
  def formatDateTime(date: String, gs: String): String = {
    var dateString = ""
    val dateTimeFormat1 = new SimpleDateFormat(gs)
    try { //先将String类型转成Date
      val date1 = dateTimeFormat1.parse(date)
      //将Date类型转成固定格式的String
      val tempDate = Calendar.getInstance
      tempDate.setTime(date1)
      val dateTimeFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
      dateString = dateTimeFormat2.format(tempDate.getTime)
    } catch {
      case e: ParseException =>
        e.printStackTrace()
    }
    dateString
  }


  /**
    * 格式日期yyyy-MM-dd'T'HH:mm:ss
    *
    * @return
    */
  def formatDateTimeT(date: Date): String = {
    val tempDate = Calendar.getInstance
    tempDate.setTime(date)
    val dateTimeTFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
    dateTimeTFormat.format(tempDate.getTime)
  }

  /**
    * 格式日期yyyyMMddHHmm
    *
    * @return
    */
  def dateTimeFormatYMDHM(date: Date): String = {
    val tempDate = Calendar.getInstance
    tempDate.setTime(date)
    val dateTimeFormatYMDHM = new SimpleDateFormat("yyyyMMddHHmmss")
    dateTimeFormatYMDHM.format(tempDate.getTime)
  }

  /**
    * 格式日期yyyyMMddHHmmss
    *
    * @return
    */
  def dateTimeFormatYMDHMS(date: Date): String = {
    val tempDate = Calendar.getInstance
    tempDate.setTime(date)
    val dateTimeFormatYMDHMS = new SimpleDateFormat("yyyyMMddHHmmss")
    dateTimeFormatYMDHMS.format(tempDate.getTime)
  }

  /**
    * 获取00:00:00
    *
    * @param date
    * @return
    */
  def getDayStart(date: Date): Date = {
    val c = Calendar.getInstance
    c.setTime(date)
    c.set(Calendar.HOUR_OF_DAY, 0)
    c.set(Calendar.MINUTE, 0)
    c.set(Calendar.SECOND, 0)
    c.set(Calendar.MILLISECOND, 0)
    c.getTime
  }

  /**
    * 获取23:59:59
    *
    * @param date
    * @return
    */
  def getDayEnd(date: Date): Date = {
    val c = Calendar.getInstance
    c.setTime(date)
    c.set(Calendar.HOUR_OF_DAY, 23)
    c.set(Calendar.MINUTE, 59)
    c.set(Calendar.SECOND, 59)
    c.set(Calendar.MILLISECOND, 999)
    c.getTime
  }

  /**
    * 获取一个较早的时间
    *
    * @return
    */
  def getEarlyDate: Date = {
    val dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    try
      return dateTimeFormat.parse(EARLYDATE)
    catch {
      case e: ParseException =>
        e.printStackTrace()
    }
    null
  }

  /**
    * 比对时间是否过期
    *
    * @param startTime
    * @param endTime
    * @return
    */
  def isRightTime(startTime: Date, endTime: Date): Boolean = {
    var result = true
    val now = new Date
    if (startTime != null && now.before(startTime)) result = false
    if (endTime != null && now.after(endTime)) result = false
    result
  }

  /**
    * 获取当前日期的前七天
    *
    * @return
    */
  def getWeekTime: util.Map[Integer, AnyRef] = {
    val map = new util.HashMap[Integer, AnyRef]
    val dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd")
    var i = 6
    while ( {
      i >= 0
    }) {
      val c = Calendar.getInstance
      c.setTime(new Date)
      c.add(Calendar.DATE, -i)
      val d = c.getTime
      val day = dateTimeFormat.format(d)
      map.put(i, day)

      {
        i -= 1; i + 1
      }
    }
    map
  }

  def getWeeks: util.List[String] = {
    val list = new util.ArrayList[String]
    val dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd")
    var i = 6
    while ( {
      i >= 0
    }) {
      val c = Calendar.getInstance
      c.setTime(new Date)
      c.add(Calendar.DATE, -i)
      val d = c.getTime
      val day = dateTimeFormat.format(d)
      list.add(day)

      {
        i -= 1; i + 1
      }
    }
    list
  }

  /**
    * 获取当前日期的前第8天
    *
    * @return
    */
  def getEightDate(i: Int): String = {
    val dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd")
    val c = Calendar.getInstance
    c.setTime(new Date)
    c.add(Calendar.DATE, -i)
    val d = c.getTime
    val day = dateTimeFormat.format(d)
    day
  }

  def getDate(dateTime: String): Date = {
    val format = getDateFormat(dateTime)
    val dateTimeFormat = new SimpleDateFormat(format)
    try
      return dateTimeFormat.parse(dateTime)
    catch {
      case e: ParseException =>
        e.printStackTrace()
    }
    null
  }

  /**
    * 常规自动日期格式识别
    *
    * @param str 时间字符串
    * @return Date
    * @author dc
    */
  private def getDateFormat(str: String) = {
    var year = false
    val pattern = Pattern.compile("^[-\\+]?[\\d]*$")
    if (pattern.matcher(str.substring(0, 4)).matches) year = true
    val sb = new StringBuilder
    var index = 0
    if (!year) if (str.contains("月") || str.contains("-") || str.contains("/")) if (Character.isDigit(str.charAt(0))) index = 1
    else index = 3
    var i = 0
    while ( {
      i < str.length
    }) {
      val chr = str.charAt(i)
      if (Character.isDigit(chr)) {
        if (index == 0) sb.append("y")
        if (index == 1) sb.append("M")
        if (index == 2) sb.append("d")
        if (index == 3) sb.append("H")
        if (index == 4) sb.append("m")
        if (index == 5) sb.append("s")
        if (index == 6) sb.append("S")
      }
      else {
        if (i > 0) {
          val lastChar = str.charAt(i - 1)
          if (Character.isDigit(lastChar)) index += 1
        }
        sb.append(chr)
      }

      {
        i += 1; i - 1
      }
    }
    sb.toString
  }

  /**
    *
    * @param strDate
    * @return
    */
  def strToDate(strDate: String, format: String): Date = {
    val formatter = new SimpleDateFormat(format)
    var strtodate:Date = null
    try{
      strtodate = formatter.parse(strDate)
    }
    catch {
      case e: ParseException =>
        e.printStackTrace()
    }
    strtodate
  }

  /**
    * 将毫秒数转化为日期字符串
    */
  def getStrDateFromLong(time: Long): String = {
    val simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
    //12小时制
    val date = new Date
    date.setTime(time)
    simpleDateFormat.format(date)
  }

  /**
    * 获取当前日期
    *
    * @return
    */
  def getDate: String = SDF_DATE.format(new Date)

  /**
    * 按指定的格式返回当前时间
    *
    * @param format
    * @return
    */
  def getFormatDate(format: String): String = new SimpleDateFormat(format).format(new Date)

  /**
    * 获取当前时间
    *
    * @return
    */
  def getTime: String = SDF_TIME.format(new Date)

  /**
    * 获取当前日期时间
    *
    * @return
    */
  def getDateTime: String = SDF_DATE_TIME.format(new Date)

  /**
    * 字符串时间格式判断
    *
    * @param date
    * @param format
    * @return
    */
  def isOK(date: String, format: String): Boolean = {
    try {
      val simpleDateFormat = new SimpleDateFormat(format)
      simpleDateFormat.setLenient(false)
      simpleDateFormat.parse(date)
    } catch {
      case e: ParseException =>
        return false
    }
    true
  }

  /**
    * 简单的当前时间加点
    */
  def addTime(add: Long): String = {
    val date = new Date().getTime
    SDF_DATE_TIME.format(new Date(date + add))
  }

  /**
    * 时间比较
    *
    * @throws ParseException 返回异常时间格式错误
    */
  @throws[ParseException]
  def compare_date(time1: String, time2: String, sdf: SimpleDateFormat): Boolean = {
    val date1 = sdf.parse(time1)
    val date2 = sdf.parse(time2)
    date1.getTime > date2.getTime
  }

  /**
    * 获取固定格式的时间
    *
    * @return
    */
  def formatStr(inputDate: String): String = {
    if (inputDate == null) return ""
    SDF_DATE_TIME.format(inputDate.toLong)
  }

  def formatStr(inputDate: String, format: String): String = {
    if (inputDate == null) return ""
    val sdf = new SimpleDateFormat(format)
    sdf.format(inputDate.toLong)
  }

  /**
    * 将字符串转为毫秒
    *
    * @param inputDate
    * @return
    * @throws ParseException
    */
  @throws[ParseException]
  def parseLong(inputDate: String): Long = {
    if (inputDate == null) return 0L
    SDF_DATE_TIME.parse(inputDate).getTime
  }

  /**
    * 将String转换成特定格式的字符串
    *
    * @param inputDate
    * @param inputFormat
    * @param outputFormat
    * @return
    */
  def formatStr(inputDate: String, inputFormat: String, outputFormat: String): String = {
    if (inputDate == null) return ""
    val sim = new SimpleDateFormat(inputFormat)
    val sim1 = new SimpleDateFormat(outputFormat)
    try {
      val date = sim.parse(inputDate)
      sim1.format(date)
    } catch {
      case e: Exception =>
        e.printStackTrace()
        null
    }
  }

  def main(args: Array[String]): Unit = {
    println(DateUtils.formatStr("201205120012", "yyyyMMddHHmm", FMT_DATE_TIME))
    println(DateUtils.formatStr("2012-05-12 00:12:00", "yyyy-MM-dd HH:mm", DateUtils.FMT_DATE))
    //String currentDate = DateUtil.getDate();
    // currentDate = currentDate.substring(0,currentDate.length() - 3).replace("-","");
    // System.out.println(currentDate);
    // System.out.println(getDateTime().replaceAll("-",""));
    // System.out.println(1L * 30 * 24 * 3600 * 1000);
    //System.out.println(getDateTime().replaceAll("-",""));
    // System.out.println(1L * 30 * 24 * 3600 * 1000);
    println(isOK("2012-05-12 12:12:12", "yyyy-MM-dd HH:mm"))

  }
}
